<?php
/**
 * session计数器
 * @param unknown $key
 * @param string $step
 * @return integer
 */
function session_counter($key=null, $step = null) {
	$namespace = '__session_counter__';
	
	// 清空计数器
	if ($key === false) {
		return session($namespace, null);
	}
	
	// 返回所有计数器数据
	if (is_null($key)) {
		return session($namespace);
	}
	
	$count = session($namespace);
	empty($count) && $count = array();
	empty($count[$key]) && $count[$key] = 0;
	
	// 获取计数值
	if (is_string($key) && is_null($step)){
		return $count[$key];
	}
	
	// 增加计数器值
	if (is_string($key) && is_numeric($step)){
		$count[$key] += $step;
		session($namespace,$count);
	}
}

/**
 * 密码加密
 *
 * @param $pwd string 明码
 * @return string 加密密码
 */
function hash_pwd($pwd) {
	return Utuo\Phpass::hash($pwd);
}

/**
 * 检测输入的验证码是否正确，$code为用户输入的验证码字符串
 *
 * @param unknown $code
 * @param string $id
 * @return boolean
 */
function check_verify($code, $id = '') {
	$verify = new \Think\Verify();
	return $verify->check($code, $id);
}

/**
 * 截取字符串，支持中英文
 *
 * @param string $str
 * @param number $start
 * @param integer $length
 * @param string $suffix
 * @param string $charset
 * @return string
 */
function cutstr($str, $start = 0, $length, $suffix = '...', $charset = null) {
	is_null($charset) && $charset = C('DEFAULT_CHARSET');
	if (function_exists("mb_substr")) {
		$slice = mb_substr($str, $start, $length, $charset);
	} elseif (function_exists('iconv_substr')) {
		$slice = iconv_substr($str, $start, $length, $charset);
		if (false === $slice) {
			$slice = '';
		}
	} else {
		$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
		$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
		$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
		$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
		preg_match_all($re[$charset], $str, $match);
		$slice = join("", array_slice($match[0], $start, $length));
	}
	$suffix = $str == $slice ? '' : $suffix;
	return $slice . $suffix;
}

/**
 * 数据绑定id
 *
 * @param array $arr 数据
 * @param string $pk 主键
 * @param string $pre 主键前缀
 * @return multitype:unknown
 */
function addID($arr, $pk = 'id', $pre = "") {
	$newArr = array ();
	foreach ($arr as $k => $v) {
		$newArr[$pre . $v[$pk]] = $v;
	}
	return $newArr;
}

/**
 * 获取网站前台链接地址
 *
 * @param unknown $controller
 * @param unknown $action
 * @param unknown $sid
 * @param unknown $params
 * @param string $domain
 */
function get_url($sid, $controller = null, $action = null, $params = array(), $domain = false) {
	// 网站首页地址
	if (empty($controller)) {
		return sprintf('http://%s/?sid=%s', $_SERVER['HTTP_HOST'], $sid);
	}
	
	// 网站栏目或内容地址
	return U("{$controller}/{$action}?sid={$sid}", $params, true, $domain);
}

/**
 * 网站链接地址
 *
 * @param integer $sid
 * @param string $module
 * @param string $controller
 * @param string $action
 * @param array $params
 * @param boolean $domain
 */
function url($module = null, $controller = null, $action = null, $params = array(), $domain = false) {
	empty($module) && $module = MODULE_NAME;
	empty($controller) && $controller = 'Index';
	empty($action) && $action = 'index';
	return U("$module/$controller/$action", $params, true, $domain);
}

/**
 * 网站链接地址
 *
 * @param integer $sid
 * @param string $module
 * @param string $controller
 * @param string $action
 * @param array $params
 * @param boolean $domain
 */
function uu($sid = 0, $module = null, $controller = null, $action = null, $params = array(), $domain = false) {
    $myDomain = M('Customer')->where("id=%d",$sid)->getField("domain");
    empty($myDomain) or $sid = $myDomain;
    empty($module) && $module = MODULE_NAME;
    empty($controller) && $controller = 'Index';
    empty($action) && $action = 'index';
    $url = U("$module/$controller/$action", $params, true, $domain);
    if ( $sid && $domain && strpos($url, ".sinaapp.com")==-1 ) {
       $host = $_SERVER["HTTP_HOST"];
       if ( strpos($url, $host) ) {
           $hostArray = explode('.', $host);
           if ( $hostArray[0] != $sid ) {
               array_unshift($hostArray, $sid);
           }
           $newHost = join('.', $hostArray);
           $url = str_replace($host, $newHost, $url);
       }
    }
    return $url;
}

/**
 * 获取网站首页地址
 *
 * @param integer $sid
 * @return string
 */
function get_site_url($sid) {
	return get_url($sid);
}

/**
 *
 * @param unknown $tableName
 * @param unknown $t 0.自动表名 1.模型名
 */
function parseTable($tableName, $t = 0) {
	if ($t)
		return '__' . strtoupper($tableName) . '__';
	else
		return preg_replace_callback('/_(\w{1})/', function ($matches) {
			return strtoupper($matches[1]);
		}, $tableName);
}

/**
 * 转换为数组
 *
 * @param unknown $values
 * @param number $mutisel 0.单选 1.多选 2.自动
 * @return array('属性id' => array('属性值1','属性值2','属性值3'))
 */
function toArray($values, $mutisel = 2, $ksort = 1) {
	$options = array ();
	foreach (explode(',', $values) as $v) {
		if (!empty($v)) {
			list ($k0, $v0) = explode("|", $v);
			if ($mutisel and !isset($options[$k0])) { // 多选
				$v0 = array (
						$v0 
				);
			} elseif (!$mutisel) { // 单选
			} elseif (isset($options[$k0]) and !is_array($options[$k0])) { // 自动
				$options[$k0] = array (
						$options[$k0] 
				);
			}
			($options[$k0] and is_array($options[$k0])) ? $options[$k0][] = $v0 and sort($options[$k0]) : $options[$k0] = $v0;
		}
	}
	$ksort and ksort($options);
	return $options;
}

/**
 * 数组转字符串
 *
 * @param unknown $data
 * @return string
 */
function arrayToString($data) {
	$str = "";
	foreach ($data as $k => $v) {
		if (is_array($v))
			foreach ($v as $v0) {
				$str .= $k . '|' . $v0 . ",";
			}
		else
			$str .= $k . '|' . $v . ",";
	}
	empty($str) or $str = "," . $str;
	return $str;
}

/**
 * 获得图片缩略地址
 *
 * @param unknown $image
 * @param unknown $action
 * @return Ambigous <string, mixed>
 */
function getImageUrl($image, $action = 'show') {
	return url('Api', 'Image', $action) . "?url=$image";
}

/**
 * 查看物流
 *
 * @param unknown $orderNo 运单号
 * @param unknown $expressName 物流名称
 * @return Ambigous <string, mixed>
 */
function getExpressUrl($orderNo, $expressName) {
	return url('Api', 'Express', 'getMessage', array (
			'orderNo' => $orderNo,
			'expressName' => $expressName,
	));
}

/**
 * 查看物流
 *
 * @param unknown $orderNo 运单号
 * @param unknown $expressName 物流名称
 * @return Ambigous <string, mixed>
 */
function getExpressLink($orderNo, $expressName) {
	$express = \Utuo\Express::getInstance(array('fake'=>true));
	return $express->getLinkUrl($expressName, $orderNo);
}


/**
 * 打印变量
 *
 * @param unknown $param
 */
function p($param = array()) {
	echo "<!--\n".'<div style="display:none">' . (print_r($param, true)) . '</div>'."\n-->";
}

// 列表层次
function makeListLevel($array, $fid = 0, $name = 'fid') {
	$list = array ();
	foreach ($array as $k => $v) {
		if ($v[$name] == $fid) {
			$list[$k] = $v;
			unset($array[$k]);
			$list[$k]['child'] = makeListLevel($array, $v['id'], $name);
		}
	}
	return $list;
}
